package com.example.shop.dao;

import com.example.shop.entity.Order;
import com.example.shop.entity.Products;
import com.example.shop.model.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * author: adnaan
 * create: 2023-11-07 15:57
 * Description:
 */
@Component
public class OrderDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    public ApiResponse Paginated(Integer currentPage, Integer pageSize, String userId) {
        String reges = String.format("%s%s%s", "^.*", userId, ".*$");//匹配规则

        Pattern pattern = Pattern.compile(reges, Pattern.CASE_INSENSITIVE);//正则匹配规则--pattern的常量
        Query query = new Query(Criteria.where("user_id").regex(pattern));
        //查询集合记录总数
        long total = mongoTemplate.count(query,Order.class);
        List<Order> comments = mongoTemplate.find(query.skip((currentPage - 1) * pageSize).limit(pageSize),Order.class);
        Map<String, Object> res = new HashMap<>();
        res.put("total", total);
        res.put("data", comments);

        return ApiResponse.success("200","获取成功",res);
    }

    public Products get(Query query) {
        return mongoTemplate.findOne(query, Products.class);
    }

    public ApiResponse save(Order order) {
        return ApiResponse.success("200","修改成功",mongoTemplate.save(order));
    }
}
